<?php

class Blog_model extends Model {

	function Blog_model()
	{
		parent::Model();	
	}
	
  /**
   * Select latest posts to display on blog homepage
   *
   * @param integer $limit the number of posts to retrieve
   * @param integer $offset the offset number to start retrieving
   * @return array an array containing all the information from the latest post database table
   */
	function select_latestPostList($limit, $offset)
	{
		$this->db->where(array('parentid' => '0'))->orderby('updated', 'DESC');
		$query = $this->db->get('posts', $limit, $offset);
		
    return $query->result_array();
	}
	
  /**
   * Count how many comments are there for a specified post
   *
   * @param integer $id the post id
   * @return integer the number of comments
   */
	function count_postComments($id)
	{
		$this->db->where(array('parentid' => $id))->orderby('posted', 'DESC');
		$query = $this->db->get('posts');
	  
	  return $query->num_rows();
	}
	
  /**
   * Select more content from the post
   *
   * @param integer $id the post id
   * @return string the content
   */
	function select_postContentMore($id)
	{
	  $this->db->select('body');
		$this->db->where(array('id' => $id));
		$query = $this->db->get('posts');
		$result = $query->result_array();
	  
	  return $result[0]['body'];
	}
	
  /**
   * Select the post and its comments
   *
   * @param string $permalink the permalink of the post
   * @return array an array containing all the information about the post and its comments
   */
	function select_postWithComments($permalink)
	{
	  // main post
	  $this->db->where(array('permalink' => $permalink));
	  $queryPost = $this->db->get('posts');
	  $result = $queryPost->result_array();
	  
	  // comments
	  $this->db->where(array('parentid' => $result[0]['id']));
	  $queryComments = $this->db->get('posts');
	  $resultComments = $queryComments->result_array();
	  
	  // combine the results
	  $result[0]['comments'] = $resultComments;
	  
	  return $result[0];
	}
}
?>